觀前提醒:
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Note:
-3
and the output represents the signed integer-1073741825
.Follow up:
If this function is called many times, how would you optimize it?
Constraints:
length = 32
利用 JS 本身內建函式的特性,來幫忙直接解題
0
,給補回來。
/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function (n) {
let arrOfN = n.toString(2).padStart(32, "0").split("").reverse();
let result = parseInt(arrOfN.join(""), 2);
return result;
};
上述為調用內部函式的解法~
但其實還有 Bitwise operattion
的操作方式,也歡迎大家換個方式,來解這題~
謝謝大家的收看,LeetCode 小學堂我們下次見~